package com.gzhryc.shared_device.oem.micro.api.controllers.xcx.v1;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.gzhryc.common.ClassTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.PayServiceFactory.AppConfig;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.LoginMemberSessionManager;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberEnum;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.AliLoginCheckRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.AliLoginCheckResponse;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.AliRegisterRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.AliRegisterResponse;

public class AliEntryController {

	static Logger log = Logger.getLogger(AliEntryController.class);
	
	@Route(value = { "/xcx/v1/ali/login/check.do" })
	public AliLoginCheckResponse checkLogin(HttpServletRequest request) {
		AliLoginCheckResponse apiResp = new AliLoginCheckResponse(ClientAPICodeConstants.EXECUTE_ERROR, "登陆失败，请稍后再试！");
		AliLoginCheckRequest apiReq = WebUtils.getJsonRequest(request, AliLoginCheckRequest.class);
		if (apiReq != null) {
			String appId = apiReq.getBody().getAppId();
			String code = apiReq.getBody().getCode();
			if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(code)) {
				log.info("[/xcx/v1/ali/login/check.do]参数：code = " + code + "，appId = " + appId);
				AlipaySystemOauthTokenResponse oauthTokenResp = PayServiceFactory.self().getOauthAccessToken(appId,code);
				if (oauthTokenResp != null) {
					log.info("获取支付宝Token信息：{{0:json}}", oauthTokenResp);
					MemberService memberService = MemberService.self();
					try {
						Member member = memberService.getByTypeAndExId(MemberEnum.Type.AliUser.index(),appId,oauthTokenResp.getOpenId());
						if(member == null) {
							member = new Member();
							member.setNickname(MicroConstants.MemberDefaultName);
							member.setType(MemberEnum.Type.AliUser.index());
							member.setAppId(appId);
							member.setOpenId(oauthTokenResp.getOpenId());
							member = memberService.add(member);
							if (member == null) {
								throw new LogicException("注册微信用户失败");
							}
						}
						
						String loginToken = IDTools.getUUID();
						LoginMember loginMember = ClassTools.copy(new LoginMember(), member);
						loginMember.setLoginToken(loginToken);
						if (LoginMemberSessionManager.self().setMemberSession(loginMember)) {
							memberService.login(member.getId());
							String resDomain = MicroConstants.getResDomain(request);
							apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
							apiResp.getBody().setMemberId(member.getId().toString());
							apiResp.getBody().setMemberName(member.getNickname());
							apiResp.getBody().setMemberFaceImg(WebUtils.setHttpDomain(resDomain,member.getFaceImg()));
							apiResp.getBody().setLoginToken(loginToken);

							if (StringTools.isNotBlank(member.getPhone())) {
								apiResp.getBody().setMemberPhone(member.getPhone());
								apiResp.getBody().setLoginLevel(3);
							} else if (MicroConstants.MemberDefaultName.equals(member.getNickname())) {
								apiResp.getBody().setLoginLevel(1);
							} else {
								apiResp.getBody().setLoginLevel(2);
							}
						} else {
							log.error("缓存会员信息失败，会员信息：{{0:json}}", member);
						}
					} catch (Exception e) {
						log.error(e.getMessage(), e);
					}
				} else {
					log.error("未找到指定的支付宝配置，APPID={{0}}", appId);
				}
			}
		}
		return apiResp;
	}

	@Route(value = { "/xcx/v1/ali/phone/register.do" })
	public AliRegisterResponse registerPhone(HttpServletRequest request) {
		AliRegisterResponse apiResp = new AliRegisterResponse(ClientAPICodeConstants.EXECUTE_ERROR, "注册失败，请稍后再试！");
		AliRegisterRequest apiReq = WebUtils.getJsonRequest(request, AliRegisterRequest.class);
		if (apiReq != null) {
			String encryptedData = apiReq.getBody().getEncryptedData();
			String appId = apiReq.getBody().getAppId();
			Long memberId = apiReq.getBody().getMemberId();
			if (StringUtils.isNotBlank(encryptedData) && StringUtils.isNotBlank(appId)) {
				AppConfig config = PayServiceFactory.self().getAliConfig(appId);
				
				Map<String, Object> map = JsonTools.fromJson(apiReq.getBody().getEncryptedData());
				if(map != null && map.containsKey("response")) {
					Object content = map.get("response");
					if(content != null) {
						//TODO 添加签名验证
						
						try {
							String charset = "UTF-8";
							String encryptType = "AES";
							String decryptKey = config.getAppSecret();
							String json = AlipayEncrypt.decryptContent(content.toString(), encryptType, decryptKey, charset);
							log.info("获取支付宝手机解析内容：{{0}}", json);
							
							map = JsonTools.fromJson(json);
							Object obj = map.get("mobile");
							if (obj != null) {
								MemberService memberService = MemberService.self();
								
								String phone = obj.toString();
								Member member = memberService.getById(memberId);
								if (member != null) {
									if(StringTools.isNotBlank(member.getPhone())){
										apiResp.setMsg("会员已注册手机号");
										return apiResp;
									}
									if(memberService.updatePhone(member.getId(),phone)) {
										String loginToken = IDTools.getUUID();
										LoginMember loginMember = ClassTools.copy(new LoginMember(), member);
										loginMember.setLoginToken(loginToken);
										if (LoginMemberSessionManager.self().setMemberSession(loginMember)) {
											memberService.login(member.getId());
											String resDomain = MicroConstants.getResDomain(request);
											apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
											apiResp.getBody().setMemberId(member.getId().toString());
											apiResp.getBody().setMemberName(member.getNickname());
											apiResp.getBody().setMemberPhone(phone);
											apiResp.getBody().setMemberFaceImg(WebUtils.setHttpDomain(resDomain, member.getFaceImg()));
											apiResp.getBody().setLoginToken(loginToken);
										}
									}
								}
							}
							
						} catch (AlipayApiException e) {
							log.error(e.getMessage(), e);
							apiResp.setMsg("支付宝解码失败，请联系客服");
							return apiResp;
						}
					}else {
						apiResp.setMsg("支付宝授权失败，请删除小程序重新扫码");
						return apiResp;
					}
				}
			}
		}
		return apiResp;
	}
}
